<template>
  <div class="distribution-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>配货单管理</h2>
      <p>管理配货单的拣货、打包、装车、配送状态跟踪</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="配货单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入配货单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="待拣货" value="pending" />
            <el-option label="拣货中" value="picking" />
            <el-option label="待打包" value="packing" />
            <el-option label="待装车" value="loading" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="异常" value="exception" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.deliveryDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleCreate" :icon="Plus">新建配货单</el-button>
        <el-button type="success" @click="handleBatchPrint" :icon="Printer" :disabled="!selectedRows.length">批量打印</el-button>
        <el-button type="warning" @click="handleBatchExport" :icon="Download" :disabled="!selectedRows.length">批量导出</el-button>
        <el-button type="info" @click="handleRefresh" :icon="Refresh">刷新</el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="配货单号" width="140" fixed="left">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="customerAddress" label="配送地址" width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="配送状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalItems" label="商品数量" width="100" />
        <el-table-column prop="totalWeight" label="总重量(kg)" width="120" />
        <el-table-column prop="deliveryDate" label="配送日期" width="120" />
        <el-table-column prop="driverName" label="配送司机" width="100" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">{{ getPriorityText(row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)" :icon="View">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" :icon="Edit" v-if="row.status !== 'completed'">编辑</el-button>
            <el-dropdown @command="(command) => handleCommand(command, row)" trigger="click">
              <el-button type="info" size="small" :icon="MoreFilled">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="track" :icon="Location">跟踪配送</el-dropdown-item>
                  <el-dropdown-item command="print" :icon="Printer">打印单据</el-dropdown-item>
                  <el-dropdown-item command="cancel" :icon="Close" v-if="row.status === 'pending'">取消配货</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑配货单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配货单号" prop="orderNo">
              <el-input v-model="formData.orderNo" placeholder="系统自动生成" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-select v-model="formData.customerName" placeholder="请选择客户" filterable style="width: 100%">
                <el-option label="华润万家" value="华润万家" />
                <el-option label="沃尔玛" value="沃尔玛" />
                <el-option label="家乐福" value="家乐福" />
                <el-option label="大润发" value="大润发" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="配送地址" prop="customerAddress">
              <el-input v-model="formData.customerAddress" placeholder="请输入配送地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="请选择配送日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送司机" prop="driverName">
              <el-select v-model="formData.driverName" placeholder="请选择司机" style="width: 100%">
                <el-option label="张师傅" value="张师傅" />
                <el-option label="李师傅" value="李师傅" />
                <el-option label="王师傅" value="王师傅" />
                <el-option label="赵师傅" value="赵师傅" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="vehicleNo">
              <el-select v-model="formData.vehicleNo" placeholder="请选择车辆" style="width: 100%">
                <el-option label="京A12345" value="京A12345" />
                <el-option label="京B67890" value="京B67890" />
                <el-option label="京C11111" value="京C11111" />
                <el-option label="京D22222" value="京D22222" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 配货单详情对话框 -->
    <el-dialog v-model="detailVisible" title="配货单详情" width="90%">
      <div class="detail-container" v-if="currentRow">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="配货单号">{{ currentRow.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentRow.customerName }}</el-descriptions-item>
          <el-descriptions-item label="配送状态">
            <el-tag :type="getStatusType(currentRow.status)">{{ getStatusText(currentRow.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="配送地址" :span="2">{{ currentRow.customerAddress }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(currentRow.priority)" size="small">{{ getPriorityText(currentRow.priority) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="配送日期">{{ currentRow.deliveryDate }}</el-descriptions-item>
          <el-descriptions-item label="配送司机">{{ currentRow.driverName }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ currentRow.vehicleNo }}</el-descriptions-item>
          <el-descriptions-item label="商品数量">{{ currentRow.totalItems }}</el-descriptions-item>
          <el-descriptions-item label="总重量">{{ currentRow.totalWeight }}kg</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentRow.createTime }}</el-descriptions-item>
        </el-descriptions>

        <!-- 配送进度 -->
        <div class="progress-section">
          <h3>配送进度</h3>
          <el-steps :active="getStepActive(currentRow.status)" finish-status="success">
            <el-step title="待拣货" description="等待仓库拣货" />
            <el-step title="拣货中" description="仓库正在拣货" />
            <el-step title="待打包" description="等待打包" />
            <el-step title="待装车" description="等待装车" />
            <el-step title="配送中" description="正在配送" />
            <el-step title="已完成" description="配送完成" />
          </el-steps>
        </div>

        <!-- 商品明细 -->
        <div class="items-section">
          <h3>商品明细</h3>
          <el-table :data="currentRow.items" border>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="weight" label="重量(kg)" />
            <el-table-column prop="pickStatus" label="拣货状态">
              <template #default="{ row }">
                <el-tag :type="row.pickStatus === 'completed' ? 'success' : 'warning'">
                  {{ row.pickStatus === 'completed' ? '已拣货' : '待拣货' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  View,
  Delete,
  Download,
  Printer,
  MoreFilled,
  Location,
  Close
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')
const currentRow = ref(null)
const selectedRows = ref([])
const formRef = ref(null)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  customerName: '',
  deliveryDate: []
})

// 表单数据
const formData = reactive({
  orderNo: '',
  customerName: '',
  customerAddress: '',
  deliveryDate: '',
  priority: 'medium',
  driverName: '',
  vehicleNo: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  customerAddress: [{ required: true, message: '请输入配送地址', trigger: 'blur' }],
  deliveryDate: [{ required: true, message: '请选择配送日期', trigger: 'change' }],
  driverName: [{ required: true, message: '请选择配送司机', trigger: 'change' }],
  vehicleNo: [{ required: true, message: '请选择车辆', trigger: 'change' }]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    orderNo: 'PH202401001',
    customerName: '华润万家',
    customerAddress: '北京市朝阳区建国路88号',
    status: 'delivering',
    totalItems: 25,
    totalWeight: 150.5,
    deliveryDate: '2024-01-15',
    driverName: '张师傅',
    vehicleNo: '京A12345',
    priority: 'high',
    createTime: '2024-01-14 09:30:00',
    items: [
      { productName: '可口可乐', specification: '330ml*24瓶', quantity: 10, unit: '箱', weight: 8.5, pickStatus: 'completed' },
      { productName: '康师傅方便面', specification: '袋装', quantity: 50, unit: '包', weight: 12.0, pickStatus: 'completed' }
    ]
  },
  {
    id: 2,
    orderNo: 'PH202401002',
    customerName: '沃尔玛',
    customerAddress: '上海市浦东新区世纪大道1000号',
    status: 'packing',
    totalItems: 18,
    totalWeight: 95.2,
    deliveryDate: '2024-01-15',
    driverName: '李师傅',
    vehicleNo: '京B67890',
    priority: 'medium',
    createTime: '2024-01-14 10:15:00',
    items: [
      { productName: '农夫山泉', specification: '550ml*24瓶', quantity: 8, unit: '箱', weight: 15.2, pickStatus: 'completed' },
      { productName: '奥利奥饼干', specification: '盒装', quantity: 30, unit: '盒', weight: 6.5, pickStatus: 'pending' }
    ]
  },
  {
    id: 3,
    orderNo: 'PH202401003',
    customerName: '家乐福',
    customerAddress: '广州市天河区天河路208号',
    status: 'picking',
    totalItems: 32,
    totalWeight: 180.8,
    deliveryDate: '2024-01-16',
    driverName: '王师傅',
    vehicleNo: '京C11111',
    priority: 'low',
    createTime: '2024-01-14 11:20:00',
    items: [
      { productName: '统一绿茶', specification: '500ml*15瓶', quantity: 12, unit: '箱', weight: 9.8, pickStatus: 'pending' },
      { productName: '好丽友派', specification: '盒装', quantity: 25, unit: '盒', weight: 8.2, pickStatus: 'pending' }
    ]
  },
  {
    id: 4,
    orderNo: 'PH202401004',
    customerName: '大润发',
    customerAddress: '深圳市南山区深南大道9988号',
    status: 'completed',
    totalItems: 45,
    totalWeight: 220.3,
    deliveryDate: '2024-01-14',
    driverName: '赵师傅',
    vehicleNo: '京D22222',
    priority: 'urgent',
    createTime: '2024-01-13 14:30:00',
    items: [
      { productName: '雪碧', specification: '330ml*24瓶', quantity: 15, unit: '箱', weight: 12.5, pickStatus: 'completed' },
      { productName: '德芙巧克力', specification: '盒装', quantity: 40, unit: '盒', weight: 18.8, pickStatus: 'completed' }
    ]
  },
  {
    id: 5,
    orderNo: 'PH202401005',
    customerName: '华润万家',
    customerAddress: '成都市锦江区春熙路169号',
    status: 'pending',
    totalItems: 28,
    totalWeight: 165.7,
    deliveryDate: '2024-01-17',
    driverName: '张师傅',
    vehicleNo: '京A12345',
    priority: 'medium',
    createTime: '2024-01-14 15:45:00',
    items: [
      { productName: '百事可乐', specification: '330ml*24瓶', quantity: 12, unit: '箱', weight: 8.8, pickStatus: 'pending' },
      { productName: '乐事薯片', specification: '袋装', quantity: 35, unit: '包', weight: 7.5, pickStatus: 'pending' }
    ]
  }
]

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    picking: 'warning',
    packing: 'warning',
    loading: 'warning',
    delivering: 'primary',
    completed: 'success',
    exception: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待拣货',
    picking: '拣货中',
    packing: '待打包',
    loading: '待装车',
    delivering: '配送中',
    completed: '已完成',
    exception: '异常'
  }
  return statusMap[status] || '未知'
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const priorityMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || '未知'
}

// 获取步骤激活状态
const getStepActive = (status) => {
  const stepMap = {
    pending: 0,
    picking: 1,
    packing: 2,
    loading: 3,
    delivering: 4,
    completed: 5,
    exception: -1
  }
  return stepMap[status] || 0
}

// 加载数据
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    status: '',
    customerName: '',
    deliveryDate: []
  })
  loadData()
}

// 刷新
const handleRefresh = () => {
  loadData()
}

// 新建
const handleCreate = () => {
  isEdit.value = false
  dialogTitle.value = '新建配货单'
  Object.assign(formData, {
    orderNo: 'PH' + new Date().getFullYear() + (new Date().getMonth() + 1).toString().padStart(2, '0') + new Date().getDate().toString().padStart(2, '0') + Math.floor(Math.random() * 1000).toString().padStart(3, '0'),
    customerName: '',
    customerAddress: '',
    deliveryDate: '',
    priority: 'medium',
    driverName: '',
    vehicleNo: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑配货单'
  Object.assign(formData, {
    orderNo: row.orderNo,
    customerName: row.customerName,
    customerAddress: row.customerAddress,
    deliveryDate: row.deliveryDate,
    priority: row.priority,
    driverName: row.driverName,
    vehicleNo: row.vehicleNo,
    remark: row.remark || ''
  })
  currentRow.value = row
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  currentRow.value = row
  detailVisible.value = true
}

// 命令处理
const handleCommand = (command, row) => {
  switch (command) {
    case 'track':
      ElMessage.info('跟踪配送功能开发中...')
      break
    case 'print':
      ElMessage.success('正在打印配货单...')
      break
    case 'cancel':
      ElMessageBox.confirm('确定要取消此配货单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success('配货单已取消')
        loadData()
      })
      break
  }
}

// 批量打印
const handleBatchPrint = () => {
  ElMessage.success(`正在打印 ${selectedRows.value.length} 个配货单...`)
}

// 批量导出
const handleBatchExport = () => {
  ElMessage.success(`正在导出 ${selectedRows.value.length} 个配货单...`)
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '配货单更新成功' : '配货单创建成功')
        submitLoading.value = false
        dialogVisible.value = false
        loadData()
      }, 1000)
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.distribution-order-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  padding: 20px 0;
}

.progress-section,
.items-section {
  margin-top: 30px;
}

.progress-section h3,
.items-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .distribution-order-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>